<template>
  <div>
    <!--面包屑导航-->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!--卡片部分-->
    <el-card>
      <!--alert警告部分-->
      <el-alert
        title="注意：只允许为第三级分类设置相关参数！" :closable="false"
        type="warning" show-icon>
      </el-alert>
      <!--选择商品级联选择器表单-->
      <el-row class="chooseCate">
        <el-col>
          <span>选择商品分类:</span>
          <el-cascader
            v-model="selectedKey"
            :options="catelist"
            :props="cascaderProps"
            clearable change-on-select @change="cateChanged">
          </el-cascader>
        </el-col>
      </el-row>
      <!--静态参数动态属性菜单栏-->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane label="动态参数" name="many">
          <!--动态参数添加参数按钮-->
          <el-button type="primary" size="mini" @click="showAddParamDialog" :disabled="isBtnDisabled">添加参数</el-button>
          <!--动态参数表格-->
          <el-table :data="manyTableData" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag v-for="(item, index) in scope.row.attr_vals" :key="index" closable @close="handleTagClose(index, scope.row)">{{item}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button icon="el-icon-edit" size="mini" type="primary" @click="showReviseDialog(scope.row)">修改</el-button>
                <el-button icon="el-icon-delete" size="mini" type="danger" @click="deleteParam(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <!--静态属性添加属性按钮-->
          <el-button type="primary" size="mini" @click="showAddParamDialog" :disabled="isBtnDisabled">添加属性</el-button>
          <!--静态属性表格-->
          <el-table :data="onlyTableData" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag v-for="(item, index) in scope.row.attr_vals" :key="index" closable @close="handleTagClose(index, scope.row)">{{item}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column label="属性名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button icon="el-icon-edit" size="mini" type="primary" @click="showReviseDialog(scope.row.attr_id)">修改</el-button>
                <el-button icon="el-icon-delete" size="mini" type="danger" @click="deleteParam(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!--添加参数对话框-->
    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="addParamsDialogVisible"
      width="50%" @close="addFormClosed">
      <el-form :model="addParamForm" :rules="addParamRules"
               ref="addParamFormRef" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addParamForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="addParamsDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addParams">确 定</el-button>
  </span>
    </el-dialog>
    <!--修改参数对话框-->
    <el-dialog
      :title="'修改' + titleText"
      :visible.sync="reviseParamDialogVisible"
      width="50%" @close="reviseFormClosed">
      <el-form :model="reviseParamForm" :rules="addParamRules"
               ref="reviseParamFormRef" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="reviseParamForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="reviseParamDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="reviseParams">确 定</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      selectedKey: [],
      catelist: [],
      cascaderProps: {
        expandTrigger: 'hover',
        label: 'cat_name',
        value: 'cat_id',
        children: 'children'
      },
      manyTableData: [],
      onlyTableData: [],
      activeName: 'many',
      addParamsDialogVisible: false,
      addParamForm: {
        attr_name: ''
      },
      addParamRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      },
      reviseParamDialogVisible: false,
      reviseParamForm: {
        attr_name: ''
      }
    }
  },
  created () {
    this.getCateList()
  },
  methods: {
    async getCateList () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.error('获取商品分类列表失败')
      this.catelist = res.data
    },
    async getParamsData () {
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: this.activeName } })
      if (res.meta.status !== 200) return this.$message.error('获取动态参数错误')
      console.log(res.data)
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        item.inputVisible = false
        item.inputValue = ''
      })
      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else if (this.activeName === 'only') {
        this.onlyTableData = res.data
      }
      return this.$message.success('获取动态参数成功')
    },
    cateChanged () {
      if (this.selectedKey.length !== 3) {
        this.selectedKey = []
        this.manyTableData = []
        this.onlyTableData = []
        return
      }
      this.getParamsData()
    },
    handleTabClick () {
      this.getParamsData()
    },
    showAddParamDialog () {
      this.addParamsDialogVisible = true
    },
    addParams () {
      this.$refs.addParamFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`, { attr_name: this.addParamForm.attr_name, attr_sel: this.activeName })
        if (res.meta.status !== 201) {
          return this.$message.error('添加属性出错')
        }
        this.$message.success('添加属性成功')
        this.getParamsData()
        this.addParamsDialogVisible = false
      })
    },
    addFormClosed () {
      this.$refs.addParamFormRef.resetFields()
    },
    async showReviseDialog (paraminfo) {
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes/${paraminfo.attr_id}`, { params: { attr_sel: this.activeName } })
      if (res.meta.status !== 200) return this.$message.error('信息获取失败')
      this.reviseParamForm = res.data
      this.reviseParamDialogVisible = true
    },
    reviseFormClosed () {
      this.$refs.reviseParamFormRef.resetFields()
    },
    reviseParams () {
      this.$refs.reviseParamFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${this.reviseParamForm.attr_id}`, { attr_name: this.reviseParamForm.attr_name, attr_sel: this.activeName })
        if (res.meta.status !== 200) return this.$message.error('属性更新失败')
        this.$message.success('属性更新成功')
        this.reviseParamDialogVisible = false
        this.getParamsData()
      })
    },
    async deleteParam (id) {
      const confirmResult = await this.$confirm('是否要删除该属性', '删除属性', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(error => error)
      if (confirmResult === 'confirm') {
        const { data: res } = await this.$http.delete(`categories/${this.cateId}/attributes/${id}`)
        if (res.meta.status !== 200) return this.$message.error('删除失败')
        this.$message.success('删除成功')
        this.getParamsData()
      } else {
        return this.$message.info('已取消了操作')
      }
    },
    handleInputConfirm (row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      this.saveAttrVals(row)
    },
    showInput (row) {
      row.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    async saveAttrVals (row) {
      const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, { attr_name: row.attr_name, attr_sel: row.attr_sel, attr_vals: row.attr_vals.join(' ') })
      if (res.meta.status !== 200) {
        return this.$message.error('参数更新错误')
      }
      return this.$message.success('参数更新成功')
    },
    handleTagClose (i, row) {
      row.attr_vals.splice(i, 1)
      this.saveAttrVals(row)
    }
  },
  computed: {
    isBtnDisabled () {
      if (this.selectedKey.length !== 3) {
        return true
      }
      return false
    },
    cateId () {
      if (this.selectedKey.length === 3) {
        return this.selectedKey[this.selectedKey.length - 1]
      }
      return null
    },
    titleText () {
      if (this.activeName === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    }
  }
}
</script>

<style lang="less" scoped>
  .chooseCate {
    margin: 15px 0;
  }
  span {
    font-size: 15px;
    margin-right: 15px;
  }
  .el-tag {
    margin: 10px;
    font-size: 12px
  }
  .input-new-tag {
    width: 120px;
  }
</style>
